package com.consumer.handsome.controller;


import com.consumer.handsome.exception.BaseException;
import com.consumer.handsome.exception.BussinessException;
import com.consumer.handsome.exception.MessageConstant;
import com.consumer.handsome.response.BaseResponse;
import com.consumer.handsome.utils.MediaTypeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("wx/")
@Slf4j
@Api(tags = "通用接口")
public class UploadController {

    @Value("${file.file-path}")
    private String uploadDir;

    @PostMapping("/upload")
    @ApiOperation(value = "单文件上传")
    public BaseResponse<String> uploadForm(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
             throw new BussinessException(MessageConstant.FAIL_ISNULL);
        }

        try {
            // 构建上传文件的保存路径
            String filePath = uploadDir ;
            File dest = new File(filePath);
            File newFile = new File(dest.getAbsolutePath() + File.separator + file.getOriginalFilename());

            // 如果保存路径不存在，则创建目录
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件到指定路径
            file.transferTo(newFile);
            String urlImg = "http://43.139.71.229:8056/wx"+"/images/"+file.getOriginalFilename();

            return new BaseResponse<>(urlImg);
        } catch (IOException e) {
            throw new BaseException(MessageConstant.UPLOAD_FAILED);
        }

    }

    @GetMapping("/images/{resourcePath}")
    public ResponseEntity<byte[]> getStaticResource(@PathVariable String resourcePath, HttpServletRequest request) throws IOException {
        Path newPath = Paths.get(uploadDir, resourcePath);

        log.info("filePath==>"+newPath);
        Resource resource = new UrlResource(newPath.toUri());

        if (resource.exists()) {
            String filename = resource.getFilename();
            String imgFormat = filename.substring(filename.lastIndexOf(".")+1);
            Path filePath = resource.getFile().toPath();
            byte[] resourceBytes = Files.readAllBytes(filePath);
            if (imgFormat.equals("docx")||imgFormat.equals("doc")){
                return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/msword"))
                        .body(resourceBytes);
            }
            else if (imgFormat.equals("mp4")){
                return ResponseEntity.ok().contentType(MediaType.parseMediaType("video/mp4"))
                        .body(resourceBytes);
            }
            else {
                MediaType mediaType = MediaTypeUtil.resolveImageMediaType(imgFormat);
                return ResponseEntity.ok().contentType(mediaType).body(resourceBytes);
            }
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
